<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>血液订购</title>
    <link rel="shortcut icon" type="image/x-icon" href="/img/favicon.ico">
    <link rel="stylesheet" href="/element-theme/blue/index.css">
    <style type="text/css">
        .amount-warp {
            display: flex;
            justify-content: center;
        }
        .amount-warp>input {
            width: 50px;
            height: 31px;
            line-height: 30px;
            padding-left: 10px;
            outline: none;
        }
        .amount-warp>.quick-button>i {
            display: block;
            width: 30px;
            height: 16px;
            border-left: none;
            text-align: center;
            line-height: 16px;
            cursor: pointer;
        }
        .border {
            border: 1px solid #a3a3a3;
        }
    </style>
</head>

<body>
    <div class="data-manage-table">
        <template>
            <!--血液订单查询-->
            <el-form ref="form" :inline="true" style="padding:20px 20px 0 20px;">
                <el-select
                        v-model="searchPriceToConfirm.bloodType"
                        placeholder="请选择血液类型"
                        clearable
                        filterable
                        @blur="selectBlur"
                        @clear="selectClear"
                        @change="selectChange"
                >
                    <el-option
                            v-for="(item,index) in applyBloodType"
                            :key="index"
                            :label="item.composition"
                            :value="item.code" />
                </el-select>
                
                <el-form-item>
                    <el-button type="primary" @click="clickSearchBloodPrice">搜索</el-button>
                    <el-button type="info" @click="emptySearch">重置</el-button>
                    <el-button type="" @click="exportExcel()">导出</el-button>
                </el-form-item>
            </el-form>
            
            <!--血液价格展示-->
            <el-table :data="bloodPriceInformation" style="width: 100%"
                :header-cell-style="{'text-align': 'center','background': '#eef1f6'}" highlight-current-row
                @current-change="" id="out-table">
                <el-table-column type="selection" min-width="10%" align="center"></el-table-column>

                <el-table-column prop="typeInfo" label="血液类型" min-width="15%" align="center">
                </el-table-column>

<!--                <el-table-column prop="bloodPrice" label="单价/元" min-width="10%" align="center">-->
<!--                </el-table-column>-->

                <el-table-column prop="measurementUnit" label="计量单位/ml" min-width="15%" align="center">
                </el-table-column>
                
                <el-table-column prop="aboInfo" label="ABO血型" min-width="20%" align="center">
                    <template slot-scope="scope">
                        <el-select
                                @change="cartGoodsAboChange($event,scope.row)" v-model="scope.row.aboInfo"
                                placeholder="请选择ABO血型"
                                clearable
                                filterable
                                @blur="selectBlur"
                                @clear="selectClear"
                        >
                            <el-option
                                    v-for="(item,index) in aboBloodType"
                                    :key="index"
                                    :label="item.name" :value="{value: item.code, label: item.name}"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column prop="rhInfo" label="RH血型" min-width="20%" align="center">
                    <template slot-scope="scope">
                        <el-select
                                @change="cartGoodsRhChange($event,scope.row)" v-model="scope.row.rhInfo"
                                placeholder="请选择RH血型"
                                clearable
                                filterable
                                @blur="selectBlur"
                                @clear="selectClear"
                        >
                            <el-option
                                    v-for="(item,index) in rhBloodType"
                                    :key="index"
                                    :label="item.name" :value="{value: item.code, label: item.name}"
                            />
                        </el-select>
                    </template>
                </el-table-column>
                

                <el-table-column label="数量" prop="title" min-width="10%" align="center">
                    <template slot-scope="scope">
                        <div class="amount-warp">
                            <input class="border" @change="cartGoodsAmountChange($event,scope.row)" v-model="scope.row.amount" />
                            <div class="quick-button">
                                <i class="border el-icon-arrow-up" @click="addAmountCount(scope.row)"></i>
                                <i class="border el-icon-arrow-down" @click="subtractAmountCount(scope.row)"></i>
                            </div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="操作"  min-width="10%" align="center">
                    <template slot-scope="scope" >
                        <el-button size="mini" type="primary" @click="addCart(scope.row)">加入购物车</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
<!--            <el-pagination :page-size="pageSize" :total="total" :current-page.sync="current" layout="prev, pager, next, jumper"-->
<!--                class="pagination"  @current-change="handleCurrentChange" style="text-align: center; margin-top: 20px;">-->
<!--            </el-pagination>-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="current"
                    :page-sizes="[1, 5, 10, 20]"
                    :page-size.sync="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    class="pagination"
                    style="text-align: center; margin-top: 20px;">
            </el-pagination>
            
            <el-button type="primary" style='position: absolute;right:10px;top:5px;' @click="toShopCart">跳转购物车</el-button>
        </template>
    </div>

    <script src="/plugins/vue-2.5.17/vue.js"></script>
    <script src="/plugins/element-2.4.5/index.js"></script>
    <script src="/icons/iconfont.js"></script>
    <script src="/js/axios.min.js"></script>

    <script>Vue.prototype.$ELEMENT = { size: 'medium' };</script>
    <script language="JavaScript" type="text/javascript">
        //Date原型上添加格式转换方法
        Date.prototype.format = function(fmt) {
            const o = {
                "M+": this.getMonth() + 1,                 //月份 
                "d+": this.getDate(),                    //日 
                "h+": this.getHours(),                   //小时 
                "m+": this.getMinutes(),                 //分 
                "s+": this.getSeconds(),                 //秒 
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                "S": this.getMilliseconds()             //毫秒 
            };
            if(/(y+)/.test(fmt)) {
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
            }
            for(const k in o) {
                if(new RegExp("("+ k +")").test(fmt)){
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
                }
            }
            return fmt;
        }
    </script>
    <script>
        (function () {
            const vm = window.vm = new Vue({
                el: '.data-manage-table',
                data() {
                    return {
                        total: 0,   //总记录数
                        current: 1,     //当前页
                        pageSize: 5,      //每页记录数
                        pages: 0,       //总页数
                        
                        //血液类型选择
                        applyBloodType: [],

                        //ABO血型
                        aboBloodType : [],

                        //RH血型
                        rhBloodType: [],

                        //搜索血液订单信息条件
                        searchBloodPriceDate: {
                            bloodType: ''
                        },

                        //已输入的搜索条件
                        searchPriceToConfirm: {
                            bloodType: ''
                        },
                        
                        //查询到的血液价格信息
                        bloodPriceInformation: [],

                        modifyFormRules: {
                            applyBloodType: [{required: true, message: '请选择血液类型', trigger: 'blur'}],
                            bloodVolume:  [{required: true, message: '请输入血量', trigger: 'blur'}],
                        }
                    }
                },

                computed: {
                    //购物车信息
                    shopCart(){
                        let shopCart = JSON.parse(sessionStorage.getItem("shopCart"))
                        if(shopCart != null)
                            return shopCart
                        else 
                            return []
                    }
                },

                watch: {
                },

                methods: {
                    selectBlur(e) {
                        if (e.target.value !== '') {
                            this.searchPriceToConfirm.bloodType = e.target.value + '(其他)';
                            this.$forceUpdate()   // 强制更新
                        }
                    },
                    selectClear() {
                        this.searchPriceToConfirm.bloodType = ''
                        this.$forceUpdate()
                    },
                    selectChange(val) {
                        this.searchPriceToConfirm.bloodType = val
                        this.$forceUpdate()
                    },

                    //每页记录个数变化
                    handleSizeChange(val) {
                        this.current = 1
                        this.pageSize = val
                        this.searchBloodPrice()
                    },

                    //点击页码
                    handleCurrentChange: function (val) {
                        this.searchBloodPrice()
                    },
                    
                    //点击查询按钮
                    clickSearchBloodPrice(){
                        this.current = 1
                        this.searchBloodPriceDate = JSON.parse(JSON.stringify(this.searchPriceToConfirm))
                        this.searchBloodPrice()
                    },

                    //查询血液价格
                    searchBloodPrice() {
                        let bloodType = this.searchBloodPriceDate.bloodType
                        axios({
                            url: '/bloodPrice/normal/searchPrice',
                            method: 'get',
                            params: {
                                bloodType: bloodType,
                                currentPage: this.current,
                                pageSize: this.pageSize
                            },
                        }).then(res => {
                            if (res.status == '200') {
                                //个每个商品添加amount字段，初始值为1
                                res.data.data.forEach((value , index) => {
                                    value.amount = 1
                                })
                                this.bloodPriceInformation = res.data.data
                                this.total = res.data.total;
                                this.pages = res.data.pages;
                            } else {
                                this.$notify({
                                    tile: '警告',
                                    message: '搜索出错',
                                    type: 'warning'
                                })
                            }
                        }).catch(err => {
                            this.$notify.error({
                                title: '错误',
                                message: '搜索失败',
                            })
                        })
                    },

                    //获取AboType和RhType，血液类型
                    getInformation: function(val) {
                        //获取AboType
                        axios({
                            url: '/aboType/normal/query',
                            method: 'get',
                            params: {},
                        }).then(res => {
                            if (res.status == 200) {
                                this.aboBloodType = res.data
                            }
                        }).catch(err => {

                        })

                        //获取RhType
                        axios({
                            url: '/rhType/normal/query',
                            method: 'get',
                            params: {},
                        }).then(res => {
                            if (res.status == 200) {
                                this.rhBloodType = res.data
                            }
                        }).catch(err => {

                        })

                        //获取BloodComposition
                        axios({
                            url: '/bloodComposition/normal/query',
                            method: 'get',
                            params: {},
                        }).then(res => {
                            if (res.status == 200) {
                                this.applyBloodType = res.data
                            }
                        }).catch(err => {

                        })
                    },
                    
                    //清空搜索条件
                    emptySearch() {
                        for (const key in this.searchPriceToConfirm)
                            this.searchPriceToConfirm[key] = ""
                        for (const key in this.searchBloodOrderDate)
                            this.searchBloodOrderDate[key] = ""
                    },

                    //选择ABO血型
                    cartGoodsAboChange(e, orderInfo) {
                        const {value, label} = e
                        let aboBloodType = value
                        let aboInfo = label
                        if (aboBloodType != "" && aboBloodType != null && aboInfo != "" && aboInfo != null) {
                            orderInfo.aboBloodType = aboBloodType
                            orderInfo.aboInfo = aboInfo
                        }
                        // let aboBloodType = e
                        // if (aboBloodType != "" && aboBloodType != null)
                        //     orderInfo.aboBloodType = aboBloodType
                        // console.log(e)
                    },

                    //选择RH血型
                    cartGoodsRhChange(e, orderInfo) {
                        const {value, label} = e
                        let rhBloodType = value
                        let rhInfo = label
                        if (rhBloodType != "" && rhBloodType != null && rhInfo != "" && rhInfo != null) {
                            orderInfo.rhBloodType = rhBloodType
                            orderInfo.rhInfo = rhInfo
                        }
                        
                        // let rhBloodType = e
                        // orderInfo.rhBloodType = rhBloodType
                        // console.log(e)
                    },

                    //输入商品数量
                    cartGoodsAmountChange(e, orderInfo){
                        let value = e.target.value * 1
                        if(value < 1 || isNaN(value))
                            orderInfo.amount = 1
                        else
                            orderInfo.amount = parseInt(value)
                    },

                    // 商品数量加1
                    addAmountCount(orderInfo) {
                        ++orderInfo.amount
                    },
                    
                    // 商品数量减1
                    subtractAmountCount(orderInfo) {
                        if (orderInfo.amount <= 1) {
                            return this.$message.error('商品数量不能小于0')
                        }
                        --orderInfo.amount
                    },
                    
                    //加入购物车
                    addCart(orderInfo){
                        if (orderInfo.aboBloodType == null || orderInfo.rhBloodType == null){
                            this.$message({
                                message: "请选择血型",
                                type: "error",
                            });
                            return;
                        }
                        let skuAmount = orderInfo.amount * 1      //加入购物车的数量
                        let exist = false   //购物车中是否存在
                        let indexExist      //存在的话是第几个商品
                        //查询商品是否存在，存在的话是第几个
                        if(this.shopCart != null && this.shopCart.length > 0){
                            this.shopCart.forEach(function (item, index) {
                                if(item.bloodType == orderInfo.bloodType && item.aboBloodType == orderInfo.aboBloodType && item.rhBloodType == orderInfo.rhBloodType){
                                    console.log("该商品已经存在")
                                    exist = true
                                    indexExist = index
                                    return
                                }
                            })
                        }
                        //购物车存在该商品
                        if(exist){
                            this.shopCart[indexExist].cartAmount += orderInfo.amount
                            orderInfo.amount = 1
                        }
                        //购物车不存在该商品
                        else {
                            let newSku = JSON.parse(JSON.stringify(orderInfo))
                            newSku.cartAmount = newSku.amount
                            delete newSku.id
                            delete newSku.amount
                            delete newSku.priceExecutionDate
                            delete newSku.priceExecutionNumber
                            this.shopCart.push(newSku)
                        }
                        let message = `加入购物车成功！ ` + '</br>' + `类型：${orderInfo.typeInfo} ` + '</br>' + `数量：${orderInfo.amount}`
                        this.$message({
                            // 将 message 就会被当作 HTML 片段处理
                            dangerouslyUseHTMLString: true,
                            message: message,
                            type: "success",
                        });
                        // this.$notify({
                        //     title: '加入购物车成功',
                        //     dangerouslyUseHTMLString: true,
                        //     message: `类型：${orderInfo.bloodType} ` + '</br>' + `数量：${orderInfo.amount}`,
                        //     type: 'success'
                        // })
                        
                        orderInfo.amount = 1
                        sessionStorage.setItem("shopCart",JSON.stringify(this.shopCart))
                        console.log(this.shopCart)
                    },
                    
                    //导出excel
                    exportExcel () {
                        let bloodType = this.searchBloodPriceDate.bloodType
                        //创建a标签元素
                        const a = document.createElement('a')
                        a.href = '/bloodPrice/normal/downloadExcel?' + 'bloodType=' + bloodType
                        a.click()
                    },
                    
                    toShopCart(){
                        window.location.href = '/shopCart'
                    }
                },

                mounted() {
                    this.searchBloodPrice()
                    this.getInformation()
                }
            });    
        })()
    </script>

</body>

</html>